package com.aos.erp.fs.show.view;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aos.erp.fs.enums.FileUriType;
import com.aos.erp.fs.model.SysFile;
import com.aos.erp.fs.show.FileView;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Component
public class AliOSSFileView implements FileView {

    @Value("${ali.oss.endPoint:}")
    private String endPoint = "";
    @Value("${ali.oss.keyId:}")
    private String keyId = "";
    @Value("${ali.oss.keySecret:}")
    private String keySecret = "";
    @Value("${ali.oss.bucketName:}")
    private String bucketName = "";

    @Override
    public FileUriType getUriType() {
        return FileUriType.aliOSS;
    }

    @Override
    public void render(HttpServletRequest request, HttpServletResponse response, SysFile sysFile) {
        OSSClient ossClient = new OSSClient(this.endPoint, this.keyId, this.keySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, sysFile.getUriSrc());
        InputStream fis = ossObject.getObjectContent();
        if (fis != null) {
            try {
                IOUtils.copy(fis, response.getOutputStream(), 1024);
                IOUtils.closeQuietly(fis, response.getOutputStream());
            } catch (FileNotFoundException e) {
                this.fileNotFound(request, response);
            } catch (IOException e) {
                log.error(sysFile.toString());
                log.error(e.getMessage(), e);
            }
        }

        ossClient.shutdown();
    }
}
